﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections;

public partial class LogEntries : BasePage
{
	protected override void pageLoad()
	{
		//SecurityCheck();
		if (!IsPostBack)
		{
			bindSections();
			bindLotTypes();
			Fill();

			string studentId = ddlStudents.SelectedValue;

			int istudentId = 0;

			if (studentId == string.Empty)
			{
				istudentId = 0;
			}
			else
			{
				istudentId = int.Parse(studentId);
			}
			bGo.Enabled = istudentId > 0;
			bAdd.Visible = istudentId > 0;

		}
	}

	protected void bindLotTypes()
	{
		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable data = dal.GetLogTypes(PAConfiguration.ConnectionString, 1, out message).Tables[0];
		PALogManager.MessageLog(message);
		DataRow dr = data.NewRow();
		dr["LOG_TYPE_ID"] = 0;
		dr["DESCRIPTION"] = "All Types";
		data.Rows.InsertAt(dr, 0);

		this.ddlTypes.DataSource = data;
		this.ddlTypes.DataBind();

	}

	protected void bindSections()
	{
		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable data = dal.GetSectionsShort(PAConfiguration.ConnectionString, Teacher.TEACHER_ID, CurrentInfo.SemesterId, out message).Tables[0];
		PALogManager.MessageLog(message);

		CheckSections(data);

		data.DefaultView.Sort = "SECTION_TITLE";
		this.ddlSections.DataSource = data;
	this.ddlSections.DataBind();


	try
	{
		if (SectionId > 0)
			ddlSections.SelectedValue = SectionId.ToString();
	}
	catch (System.Exception ex)
	{
		PALogManager.ExceptionLog(ex);
	}

		if(ddlSections.SelectedValue != string.Empty)
		bindStudents(decimal.Parse(ddlSections.SelectedValue), StudentId);
	}
	protected void bindStudents(decimal sectionId, decimal studentId)
	{
		DataLayer dal = new DataLayer();
		string message = string.Empty;

		DataTable data = dal.GetEnrolledStudents(PAConfiguration.ConnectionString, sectionId, out message);

		DataRow dr =  data.NewRow();
		dr["STUDENT_ID"] = -1;
		dr["LASTFIRST"] = " Select a Student";
		data.Rows.InsertAt(dr, 0);

		PALogManager.MessageLog(message);

		this.ddlStudents.DataSource = data;
		this.ddlStudents.DataBind();

		try
		{
			if (studentId > 0)
				ddlStudents.SelectedValue = StudentId.ToString();
		}
		catch (System.Exception ex)
		{
			PALogManager.ExceptionLog(ex);
		}


		
	}
	protected void ddlSections_SelectedIndexChanged(object sender, EventArgs e)
	{
		bindStudents(decimal.Parse(ddlSections.SelectedValue), 0);
	}

	#region Handlers

	#endregion
	protected void gvLogEntries_RowDataBound(object sender, GridViewRowEventArgs e)
	{
		if (e.Row.RowType == DataControlRowType.Header)
		{
			this.ApplySortingToHeader(e.Row.Cells);
		}

		if (e.Row.RowType != DataControlRowType.DataRow)
			return;
		if(e.Row.Cells[4].Controls.Count ==1 )

		((WebControl)e.Row.Cells[4].Controls[0]).Attributes["title"] = "Edit";
		if (e.Row.Cells[4].Controls.Count == 3)
		{
			((WebControl)e.Row.Cells[4].Controls[0]).Attributes["title"] = "Save";
			((WebControl)e.Row.Cells[4].Controls[2]).Attributes["title"] = "Cancel";
		}
		DataRow row = ((DataRowView)e.Row.DataItem).Row;

		//if ((e.Row.RowState & DataControlRowState.Normal) == DataControlRowState.Normal)
		//{
		//    if ((decimal)row["TEACHER_ID"] != Teacher.TEACHER_ID)
		//    {
		//        WebControl dcib = (WebControl)e.Row.Cells[4].Controls[0];
		//        dcib.Style["visibility"] = "hidden";
			
		//    }
		//}
		if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
		{
			DropDownList ddl = (DropDownList)e.Row.FindControl("ddList");
			if (ddl == null)
				return;
			FillType(ddl);

			try
			{
				ddl.SelectedValue = row["LOG_TYPE_ID"].ToString();
			}
			catch (System.Exception ex)
			{
				PALogManager.ExceptionLog(ex);
			}
		}
		

	}


	protected DataTable GetEntryTypes()
	{
		if (Session["LogEntriesTypes"] != null)
			return (DataTable)Session["LogEntriesTypes"];
		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable data = dal.GetLogTypes(PAConfiguration.ConnectionString, 1, out message).Tables[0];

		if (Teacher.IS_CALL_CENTER == 0)
		{
			ArrayList todelete = new ArrayList();
			foreach (DataRow dr in data.Rows)
			{
				decimal dlid = (decimal)dr["LOG_TYPE_ID"];
				if((dlid == 5) || (dlid == 6))
				{
					todelete.Add(dr);
				}
			}

			foreach (DataRow dr in todelete)
			{
				dr.Delete();
			}
		}

		PALogManager.MessageLog(message);

		Session["LogEntriesTypes"] = data;
		return data;
	}

	protected void FillType(DropDownList ddl)
	{
		ddl.DataSource = GetEntryTypes();
		ddl.DataBind();
	}
	protected void gvLogEntries_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
	{
		SetUIEnable(true);
		gvLogEntries.EditIndex = -1;
		Fill();
	}

	protected void SetUIEnable(bool flag)
	{
		gvLogEntries.AllowSorting = flag;
		ddlSections.Enabled = flag;
		ddlStudents.Enabled = flag;
		ddlTypes.Enabled = flag;
		ImageButton1.Enabled = flag;
		bGo.Enabled = flag;
		bAdd.Enabled = flag;

	}
	
	protected void gvLogEntries_RowUpdating(object sender, GridViewUpdateEventArgs e)
	{

			SetUIEnable(true);
			DataLayer dal = new DataLayer();
			string message = string.Empty;
			GridViewRow gvr = gvLogEntries.Rows[e.RowIndex];
			DropDownList ddl = (DropDownList)gvr.Cells[2].Controls[1];
			TextBox tb = (TextBox)gvr.Cells[3].Controls[1];

			decimal logtype_id = decimal.Parse(ddl.SelectedValue);

			if (DBNull.Value != gvLogEntries.DataKeys[e.RowIndex].Value)
			{
				decimal log_id = (decimal)gvLogEntries.DataKeys[e.RowIndex].Value;

				dal.UpdateLogEntries(PAConfiguration.ConnectionString,
				log_id, Teacher.TEACHER_ID, tb.Text, logtype_id, out message);

			}
			else
			{
				if (Teacher.IS_ADMIN == 0)
				{

					dal.AddLogEntries(PAConfiguration.ConnectionString,
						decimal.Parse(ddlSections.SelectedValue),
						decimal.Parse(ddlStudents.SelectedValue),
						tb.Text,
						logtype_id,
						out message);
				}
				else
				{
					DataTable sections = dal.GetSectionsShort(PAConfiguration.ConnectionString, Teacher.TEACHER_ID, CurrentInfo.SemesterId, out message).Tables[0];
					PALogManager.MessageLog(message);

					DataRow currentSection = null;

					foreach (DataRow dr in sections.Rows)
					{
						if ((decimal)dr["SECTION_ID"] == decimal.Parse(ddlSections.SelectedValue))
						{
							currentSection = dr;
							break;
						}
					}

					if ((decimal)currentSection["TEACHER_ID"] == Teacher.TEACHER_ID)
					{

						dal.AddLogEntries(PAConfiguration.ConnectionString,
							decimal.Parse(ddlSections.SelectedValue),
							decimal.Parse(ddlStudents.SelectedValue),
							tb.Text,
							logtype_id,
							out message);
					}
					else
					{
						dal.AddLogEntriesByTeacher(PAConfiguration.ConnectionString,
							Teacher.TEACHER_ID,
							decimal.Parse(ddlStudents.SelectedValue),
							tb.Text,
							logtype_id,
							out message);
					}
				}
			}

			PALogManager.MessageLog(message);

			gvLogEntries.EditIndex = -1;
			Fill();
		
	}

	protected override void Fill()
	{


		if (ddlStudents.SelectedValue == string.Empty)
			return;

		if (decimal.Parse(ddlStudents.SelectedValue) < 0)
			return;

		ImageButton1.Visible = true;

		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable data = dal.GetLogEntries(PAConfiguration.ConnectionString,
			decimal.Parse(ddlStudents.SelectedValue),
			decimal.Parse(ddlTypes.SelectedValue),
			out message).Tables[0];
		PALogManager.MessageLog(message);

		if (!string.IsNullOrEmpty(Sorting))
		{
			data.DefaultView.Sort = Sorting;
		}

		gvLogEntries.DataSource = data;
		gvLogEntries.DataBind();
	}
	protected void gvLogEntries_RowUpdated(object sender, GridViewUpdatedEventArgs e)
	{

	}
	protected void gvLogEntries_RowEditing(object sender, GridViewEditEventArgs e)
	{
		SetUIEnable(false);
		gvLogEntries.EditIndex = e.NewEditIndex;
		Fill();
	}
	protected void gvLogEntries_Sorting(object sender, GridViewSortEventArgs e)
	{
		Sort(e);
	}

	public override string Icon
	{
		get
		{
			return "images/teacher-s_log_entries-_icon.png";
		}
	}
	protected void bAdd_Click(object sender, ImageClickEventArgs e)
	{
		if (decimal.Parse(ddlStudents.SelectedValue) < 0)
			return;
		SetUIEnable(false);

		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable data = dal.GetLogEntries(PAConfiguration.ConnectionString,
			decimal.Parse(ddlStudents.SelectedValue),
			decimal.Parse(ddlTypes.SelectedValue),
			out message).Tables[0];


		DataRow dr = data.NewRow();
		dr["LOG_DATE"] = DateTime.Now;
		dr["LOG_TYPE_ID"] = ddlTypes.SelectedValue;
		dr["TEACHER_ID"] = Teacher.TEACHER_ID;
		dr["TEACHER_NAME"] = Teacher.LASTFIRST;
		data.Rows.InsertAt(dr, 0);
		gvLogEntries.EditIndex = 0;
		gvLogEntries.DataSource = data;
		gvLogEntries.DataBind();
		
	}
	protected void lbExport_Click(object sender, ImageClickEventArgs e)
	{
		if (decimal.Parse(ddlStudents.SelectedValue) < 0)
			return;

		DataLayer dal = new DataLayer();
		string message = string.Empty;
		DataTable toExcel = dal.GetLogEntries(PAConfiguration.ConnectionString,
			decimal.Parse(ddlStudents.SelectedValue),
			decimal.Parse(ddlTypes.SelectedValue),
			out message).Tables[0];
		PALogManager.MessageLog(message);


		Manager.ExportToCSV(
			Manager.PrepareLogEntriesforExport(toExcel),
			this.Context,
			"Teachers_log_Entries.csv");
	}
	protected void bGo_Click(object sender, ImageClickEventArgs e)
	{
		
		gvLogEntries.EditIndex = -1;
		Fill();
	}
	protected void ddlStudents_SelectedIndexChanged(object sender, EventArgs e)
	{
		string studentId = ddlStudents.SelectedValue;
		bGo.Enabled = int.Parse(studentId) > 0;
		bAdd.Visible = int.Parse(studentId) > 0;
	}
}
